package com.itshizhan.itjidancideveloper.minio;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class MinioUtils {
    @Autowired
    MinioProperties minioProperties;
    @Resource
    MinioClient minioClient;

    public String putObjectOfImages(InputStream inputStream,String originalFileName,String contentType){
        // Make 'asiatrip' bucket if not exist.
        //        boolean found =
        //                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getImagesBucketName()).build());
        //        if (!found) {
        //            // 桶不存在，创建一个
        //            // Make a new bucket called 'asiatrip'.
        //            // minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
        //        }

        System.out.println("上传文件原始名称名：" + originalFileName + " ,contentType:" + contentType);
        if(contentType==null){
            contentType = "application/octet-stream";
        }
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String targetFileName =  dateStr + "-" + UUID.randomUUID().toString().replace("-", "")  + suffix;
        System.out.println("上传文件targetFileName：" + targetFileName);
        try{
            // contentType 默认 application/octet-stream ，为下载
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getImagesBucketName())
                    .object(targetFileName)
                    .stream(inputStream,inputStream.available(),-1)
                    .contentType(contentType)
                    .build());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return minioProperties.getEndpoint()+"/"+minioProperties.getImagesBucketName()+"/"+targetFileName;
    }


}
